<?php
class Upload_Local{
    public  $root_path;
    private $error = ''; //上传错误信息
    public function __construct($root_path, $config = null){
        $this->root_path = $root_path;
    }
    public function checkRootPath($rootpath){
        if(!(is_writable($rootpath))){
            $this->error = '不可写'.$rootpath;
            return false;
        }
        if(!(is_dir($rootpath))){
            $this->error = '上传根目录不存在！请尝试手动创建:'.$rootpath;
            return false;
        }
        $this->root_path = $rootpath;
        return true;
    }
    public function checkSavePath($savepath){
        if (!$this->mkdir($savepath)) {
            return false;
        } else {
            if (!is_writable($this->root_path .DIRECTORY_SEPARATOR.$savepath)) {
                $this->error = '上传目录 ' . $savepath . ' 不可写！';
                return false;
            } else {
                return true;
            }
        }
    }

    public function save($file, $replace=true) {
        $filename = $this->root_path .DIRECTORY_SEPARATOR . $file['save_path']. $file['save_name'];
        if (!$replace && is_file($filename)) {
            $this->error = '存在同名文件' . $file['save_name'];
            return false;
        }
        if (!move_uploaded_file($file['tmp_name'], $filename)) {
            echo $this->error = '文件上传保存错误！';
            return false;
        }
        return true;
    }

    public function mkdir($savepath){
        $dir = $this->root_path . DIRECTORY_SEPARATOR. $savepath;
        if(is_dir($dir)){
            return true;
        }

        if(mkdir($dir, 0777, true)){
            return true;
        } else {
            echo $this->error = "目录 {$savepath} 创建失败！";
            return false;
        }
    }
    public function getError(){
        return $this->error;
    }

}
